Page({

  data: {
    device_id: 1,
    target_id: "HLD's Filter",
    services: 1,
    notifyId: 1,
    writeId: 1,
    isbegin: true,
    WIFI_ssid: "",
    WIFI_pwd: "",
    showModal: false,
    showprompt: false,
    menu: [],
  },

  add_menu(str) {
    this.data.menu.push(str);
    this.setData({
      menu: this.data.menu,
    });
  },

  initBlue: function () {
    this.add_menu("开始蓝牙配网")
    wx.openBluetoothAdapter({
      success: (res) => {
        this.add_menu("初始化蓝牙设备成功")
        this.findBlue();//2.0
      },
      fail: (res) => {//如果手机上的蓝牙没有打开，可以提醒用户
        this.add_menu("手机蓝牙未打开,请打开后重试")
      }
    })
  },
  findBlue() {
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: (res) => {
        wx.showLoading({
          title: '正在搜索设备',
        })
        this.add_menu("正在搜索设备")
        this.getBlue()
      },
      fail: (res) => {
        wx.hideLoading()
        this.add_menu("搜索附近的蓝牙设备失败")
        console.log('搜索附近的蓝牙设备失败')
      }
    })
  },
  getBlue() {
    wx.getBluetoothDevices({
      success: (res) => {
        wx.hideLoading();
        // 如果搜索到设备列表为空的话
        if (res.devices.length == 0) {
          // 监听搜索到新设备
          //  wx.showToast({
          //   title: '搜索蓝牙设备为0',
          // })
          wx.onBluetoothDeviceFound((bres) => {
            for (var i = 0; i < bres.devices.length; i++) {
              let device = bres.devices[i]
              if (device.name == this.data.target_id || device.localName == this.data.target_id) {
                this.setData({
                  device_id: bres.devices[i].deviceId
                })
                wx.showToast({
                  title: '找到蓝牙名为 ' + device.localName + ' 的蓝牙',
                })
                this.add_menu('找到蓝牙名为 ' + device.localName + ' 的蓝牙')
                this.connetBlue(this.data.device_id);//4.0
              }
              // else
              // {
              //   this.data.BLUE_list.push(device.localName);
              //   this.setData({
              //     BLUE_list: this.data.BLUE_list,
              //   });
              // }

            }
          })
          return
        } else {
          for (var i = 0; i < res.devices.length; i++) {

            // wx.showToast({
            //   title: '蓝牙名为' + res.devices[i].name,
            // })
            if (res.devices[i].name == this.data.target_id || res.devices[i].localName == this.data.target_id) {
              this.setData({
                device_id: res.devices[i].deviceId
              })
              wx.showToast({
                title: '找到蓝牙名为 ' + device.name + ' 的蓝牙',
              })
              this.add_menu('找到蓝牙名为 ' + device.localName + ' 的蓝牙')
              // this.connetBlue(res.devices[i].deviceId);//4.0
              return;
            }
          }
        }
      },
      fail: () => {

        wx.showToast({
          title: '搜索蓝牙设备失败',
        })
        this.add_menu('搜索蓝牙设备失败')
      }
    })
  },
  connetBlue(deviceId) {
    wx.createBLEConnection({
      deviceId: deviceId,//设备id
      success: (res) => {
        console.log("连接蓝牙成功!")
        this.add_menu('连接蓝牙成功')
        // 连接成功后关闭蓝牙搜索
        wx.stopBluetoothDevicesDiscovery({
          success: (res) => {
            console.log('连接蓝牙成功之后关闭蓝牙搜索');
          }
        })
        this.getServiceId()//5.0
      }
    })
  },
  getServiceId() {
    wx.getBLEDeviceServices({
      deviceId: this.data.device_id,
      success: (res) => {
        var model = res.services[0]
        this.setData({
          services: model.uuid
        })
        console.log('uuid = ' + this.data.services);
        this.add_menu('建立蓝牙服务')
        this.getCharacteId()//6.0
      }
    })
  },
  getCharacteId() {
    wx.getBLEDeviceCharacteristics({
      deviceId: this.data.device_id,
      serviceId: this.data.services,
      success: (res) => {

        for (var i = 0; i < res.characteristics.length; i++) {//2个值
          var model = res.characteristics[i]
          if (model.properties.notify == true) {
            this.setData({
              notifyId: model.uuid//监听的值
            })

            this.startNotice(model.uuid)//7.0
          }
          if (model.properties.write == true) {
            this.setData({
              writeId: model.uuid//用来写入的值
            })
          }
        }
      }
    })
  },
  startNotice(uuid) {
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: this.data.device_id,
      serviceId: this.data.services,
      characteristicId: uuid,
      success: (res) => {

        console.log('notifyBLECharacteristicValueChange success')
        this.add_menu('监听蓝牙服务')
        // 对象用来表示通用的、固定长度的原始二进制数据缓冲区。
        //不能直接操作 ArrayBuffer 的内容，而是要通过类型数组对象或 DataView 对象来操作
        // let buffer = new ArrayBuffer(9)

        // DataView 视图是一个可以从 二进制ArrayBuffer 对象中读写多种数值类型的底层接口
        // let dataView = new DataView(buffer)
        // dataView.setUint8(0, 0x20);//xx指令
        // dataView.setUint8(1, 0x43);
        wx.getConnectedWifi({
          success: (e) => {
            this.data.WIFI_ssid = e.wifi.SSID;
            this.add_menu('获取当前连接的Wi-Fi SSID')
            this.setData({
              showModal: true,
            });
          }
        })
        // let buffer = new ArrayBuffer(9)
        // let dataView = new DataView(buffer);
        // dataView.setUint8(0, 0x20);
        // dataView.setUint8(1, 0xff);
        // dataView.setUint8(2, 0x1a);
        // // buffer = this.string2buffer("01456789")
        // this.sendMy(this.data.device_id, this.data.services, uuid, buffer)
        // this.sendMy(this.data.device_id, this.data.services, uuid, buffer)
      }
    })
  },
  sendMy(deviceId, serviceId, characteristicId, buffer) {
    wx.writeBLECharacteristicValue({ // 必须先启用 notifyBLECharacteristicValueChange 才能监听到设备
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      // 这里的value是 ArrayBuffer 类型
      value: buffer,// 蓝牙设备特征值对应的二进制值
      success(res) {
        console.log('writeBLECharacteristicValue success', res)
        wx.showToast({
          title: '操作成功',
          duration: 2000
        });
      },
    })
  },
  string2buffer(str) {
    let val = ""
    if (!str) return;
    let length = str.length;
    let index = 0;
    let array = []
    while (index < length) {
      array.push(str.substring(index, index + 2));
      index = index + 2;
    }
    val = array.join(",");
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  },
  // 将ArrayBuffer转换成字符串
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  strToHexCharCode(str) {
    var hexCharCode = [];
    var chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
    console.log("str = " + str)
    for (var i = 0; i < str.length; i++) {
      console.log("str" + i + " = " + str[i])
      var bit = (str[i] & 0x0f0) >> 4;
      hexCharCode.push(chars[bit]);
      var bit = str[i] & 0x0f;
      hexCharCode.push(chars[bit]);
    }
    return hexCharCode.join("");
  },
  strToUtf8Bytes(str) {
    const utf8 = [];
    for (let ii = 0; ii < str.length; ii++) {
      let charCode = str.charCodeAt(ii);
      if (charCode < 0x80) utf8.push(charCode);
      else if (charCode < 0x800) {
        utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
      } else if (charCode < 0xd800 || charCode >= 0xe000) {
        utf8.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
      } else {
        ii++;
        charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff));
        utf8.push(
          0xf0 | (charCode >> 18),
          0x80 | ((charCode >> 12) & 0x3f),
          0x80 | ((charCode >> 6) & 0x3f),
          0x80 | (charCode & 0x3f),
        );
      }
    }
    //兼容汉字，ASCII码表最大的值为127，大于127的值为特殊字符
    for (let jj = 0; jj < utf8.length; jj++) {
      var code = utf8[jj];
      if (code > 127) {
        utf8[jj] = code - 256;
      }
    }
    return utf8;
  },

  onCancelname: function (e) {
    this.data.WIFI_pwd = "",
      this.setData({
        WIFI_pwd: this.data.WIFI_pwd
      })
  },

  onConfirmname: function (e) {
    this.data.WIFI_pwd = e.detail.value
    this.setData({
      WIFI_pwd: this.data.WIFI_pwd,
    });
  },

  sure: function (e) {
    this.setData({
      showModal: false,
    });
    this.add_menu('键入当前Wi-Fi密码完成 发送至ESP32')

    let buffer_ssid = new ArrayBuffer(this.data.WIFI_ssid.length+1)
    let hexbuffer_ssid = this.strToUtf8Bytes(this.data.WIFI_ssid)
    let dataView_ssid = new DataView(buffer_ssid);
    dataView_ssid.setUint8(0,0x55)
    for (var i = 0; i < this.data.WIFI_ssid.length ; i++) {
      dataView_ssid.setUint8(i + 1, hexbuffer_ssid[i]);
    }
    this.sendMy(this.data.device_id, this.data.services, this.data.writeId, buffer_ssid)

    let buffer = new ArrayBuffer(this.data.WIFI_pwd.length+1)
    let hexbuffer = this.strToUtf8Bytes(this.data.WIFI_pwd)
    let dataView = new DataView(buffer);
    dataView.setUint8(0,0xaa)
    for (var i = 0; i < this.data.WIFI_pwd.length ; i++) {
      dataView.setUint8(i + 1, hexbuffer[i]);
    }
    this.sendMy(this.data.device_id, this.data.services, this.data.writeId, buffer)

  },
  begin(e) {
    wx.showModal({
      title: '请确认',
      content: '确认设备是否通电并且手机已经打开蓝牙并且连接上了需要设备接入的Wi-Fi',
      success :(res) =>{
        if (res.confirm) {
          this.data.isbegin = false;
          this.setData({
            isbegin: this.data.isbegin,
          });
          this.initBlue();
        } 
      }
    })

  },
  onLoad: function (options) {
    // this.initBlue();
    // this.findBlue()
  }
})